const strFormat = require("../../util/strFormat");
const sql_check = licence => {
  return strFormat(
    "select * from bus " + 
    "where licence='{licence}';",
    { licence: licence }
  );
};
const sql_insert = data => {
  return strFormat(
    "insert into bus " + 
    "(licence, maxload, faultcondition, busload, runningcondition, speed, longitude, dimensionality, pindex) " +
    "values " + 
    "('{licence}', {maxload}, {faultcondition}, 0, 0, 0, {longitude}, {dimensionality}, {pindex}); ",
    data
  );
};

const addbus = (connection, req, res) => {
  connection.query(sql_check(req.body.data.licence), (err, result) => {
    var data = null;

    if ( err ) {
      console.error(err);
      res.status(200).json({
        status: "fail",
        data: data,
      });
      return;
    } else if ( result.length !== 0 ) {
      res.status(200).json({
        status: "warning",
        data: data,
      });
      return;
    } else {
      connection.query(sql_insert(req.body.data), (err, result) => {
        var data = null;
    
        if ( err ) {
          console.error(err);
          res.status(200).json({
            status: "fail",
            data: data,
          });
          return;
        } else {
          data = {
            licence: req.body.data.licence,
            maxload: req.body.data.maxload,
          };
    
          res.status(200).json({
            status: "success",
            data: data,
          });
        }
      });
    }
  });
}

module.exports = addbus;